package com.mind.api.serivce;

import com.alibaba.fastjson2.JSON;
import com.mind.api.WebServiceClient;
import com.mind.api.mapper.SysItongweiMessageMapper;
import com.mind.common.core.domain.entity.SysUser;
import com.mind.common.utils.StringUtils;
import com.mind.system.domain.SysConfig;
import com.mind.system.domain.SysItongweiMessage;
import com.mind.system.mapper.SysConfigMapper;
import com.mind.system.mapper.SysUserMapper;
import jakarta.annotation.PostConstruct;
import jakarta.annotation.Resource;
import lombok.extern.log4j.Log4j2;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.util.*;

@Component
@Log4j2
public class ITongweiMessage {
    private String baseUrl;

    private String jumpBaseUrl = "https://uatznsd.tongwei.com";

    private String appid;

    private String appSecret;
    private TokenRefreshThread tokenRefreshThread = new TokenRefreshThread();
    @Resource
    private WebServiceClient webServiceClient;
    @Resource
    private SysConfigMapper sysConfigMapper;

    @Resource
    private SysItongweiMessageMapper itongweiMessageMapper;

    @Resource
    private SysUserMapper sysUserMapper;

    @PostConstruct
    public void tokenThread() {
        // 2025注释
        // tokenRefreshThread.start();
    }

    public void init() {
        SysConfig baseUrlConfig = sysConfigMapper.checkConfigKeyUnique("ITONGWEIBASEURL");
        if (baseUrlConfig != null && StringUtils.isNotBlank(baseUrlConfig.getConfigValue())) {
            baseUrl = baseUrlConfig.getConfigValue();
        }

        SysConfig appidConfig = sysConfigMapper.checkConfigKeyUnique("ITONGWEIAPPID");
        if (appidConfig != null && StringUtils.isNotBlank(appidConfig.getConfigValue())) {
            appid = appidConfig.getConfigValue();
        }

        SysConfig appSecretConfig = sysConfigMapper.checkConfigKeyUnique("ITONGWEIAPPSECRET");
        if (appSecretConfig != null && StringUtils.isNotBlank(appSecretConfig.getConfigValue())) {
            appSecret = appSecretConfig.getConfigValue();
        }

        SysConfig jumpConfig = sysConfigMapper.checkConfigKeyUnique("ITONGWEIJUMPBASEURL");
        if (jumpConfig != null && StringUtils.isNotBlank(jumpConfig.getConfigValue())) {
            jumpBaseUrl = jumpConfig.getConfigValue();
        }
    }


    @Async
    public boolean sendMessage(String msgType, String content) {
        init();
        List<SysItongweiMessage> sysItongweiMessageList = itongweiMessageMapper.selectSysItongweiMessageList(new SysItongweiMessage() {{
            setStatus(1);
            setMsgType(msgType);
        }});
        log.info("sysItongweiMessageList:{}", JSON.toJSONString(sysItongweiMessageList));
        List<String> idList = new ArrayList<>();
        for (SysItongweiMessage sysItongweiMessage : sysItongweiMessageList) {
            idList.addAll(Arrays.asList(sysItongweiMessage.getRoleId().split(",")));
        }
        Set<Integer> roleIdList = new HashSet<>();
        for (String id : idList) {
            roleIdList.add(Integer.parseInt(id));
        }
        List<SysUser> sysUserList = sysUserMapper.selectByRoleIds(new ArrayList<>(roleIdList));
        log.info("sysUserList:{}", JSON.toJSONString(sysUserList));
        Set<String> msgToSet = new HashSet<>();
        for (SysUser sysUser : sysUserList) {
            String tongeweiId = sysUser.getUserName();
            if(StringUtils.isNotBlank(sysUser.getTongweiId())){
                tongeweiId = sysUser.getTongweiId();
            }
            msgToSet.add(tongeweiId);
        }
        log.info("msgToSet:{}", JSON.toJSONString(msgToSet));
        if(msgToSet.size() > 0) {
            Map<String, Object> params = new HashMap<>();
            params.put("secret", appSecret);
            params.put("appId", appid);
            params.put("msgTo", String.join(",", msgToSet));
            params.put("type", 1);
            params.put("msgContent", String.format("{\"type\":1,\"style\":\"markdown\", \"body\":\"%s \n\n [链接](%s/rule-manage/rule-check)\"}", content, jumpBaseUrl ));
            String body = webServiceClient.call(baseUrl + "/itongwei/pubMessage/send", JSON.toJSONString(params), new HashMap<String, Object>() {{
                put("Authorization", tokenRefreshThread.getToken());
            }});

            log.info("调用接口返回结果:{}", body);
        }

        return true;
    }
}
